package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Slf4j
public class MyLock implements ILock{
    private RedisTemplate redisTemplate;
    private String name;
    private static final String NAME_PREFIX="myLock:";
    private static final String ID_PREFIX=UUID.randomUUID().toString()+":";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static{
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    public MyLock(String name,RedisTemplate redisTemplate)
    {
        this.name=name;
        this.redisTemplate=redisTemplate;
    }
    public boolean tryLock(long timeoutSec) {
//        UUID.randomUUID()
        Long id = Thread.currentThread().getId();
        Boolean b = redisTemplate.opsForValue().setIfAbsent(NAME_PREFIX+name,ID_PREFIX+ id.toString(), timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    @Override
    public void unlock() {
        Long id = Thread.currentThread().getId();
        redisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(NAME_PREFIX + name),ID_PREFIX+id);
    }
}
